package com.baymax.test.scene.internal

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.view.children

class GroupedLinearLayout : LinearLayout {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    var range = setOf<RangeValue>()
        set(value) {
            field = value
            postInvalidate()
        }


    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        println("onLayout $l $r")
    }

    override fun setBackground(background: Drawable?) {
        super.setBackground(background)
    }
    override fun dispatchDraw(canvas: Canvas) {
        val n = this.range
        n.forEach {
            it.draw(canvas)
        }
        super.dispatchDraw(canvas)
    }

    fun hasIndex(index: Int): Boolean {
        return range.any { index in it.range }
    }


    data class RangeValue(
        val viewGroup: ViewGroup,
        val range: IntRange,
        val boundDrawable: GradientDrawable = GradientDrawable().apply {
            cornerRadius = 16f
            setColor(Color.BLUE)
        }
    ) {
        var open = true
        fun openRange() {
            this.open = false
            viewGroup.postInvalidate()
        }
        fun closeRange() {
            boundDrawable.setBounds(0 ,0,0,0)
            viewGroup.postInvalidate()
        }

        fun draw(canvas: Canvas) {
            if (open) {
                if (range.first != range.last && range.first >= 0 && range.last < viewGroup.childCount) {
                    val start = viewGroup.getChildAt(range.first)
                    val end = viewGroup.getChildAt(range.last)
                    val left = start.left
                    val right = end.right
                    boundDrawable.setBounds(left, viewGroup.top, right, viewGroup.height)
                } else {
                    boundDrawable.setBounds(0, 0, 0, 0)
                }
            } else {
                boundDrawable.setBounds(0, 0, 0, 0)
            }
            boundDrawable.draw(canvas)
        }
    }


}